package com.huike.utils;

import com.huike.common.config.MinioConfig;
import com.huike.utils.uuid.UUID;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class MinIOUtils {

    private MinioConfig minioConfig;

    public MinIOUtils(MinioConfig minioConfig) {
        this.minioConfig = minioConfig;
    }

    /**
     * 文件上传
     *
     * @return
     */
    public String upload(MultipartFile file) throws Exception {
        //1. 构建客户端对象 MinioClient
        MinioClient minioClient = getMinioClient();

        //2. 判断bucket是否存在, 不存在则创建
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucketName()).build());
        }

        //3. 构建对象名称 -- 2023/06/xxxxxxxxxxx.pdf
        String originalFilename = file.getOriginalFilename();
        String dir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/"));
        String objectName = dir + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //4. 文件上传
        PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        minioClient.putObject(putObjectArgs);

        //5. 返回存储路径
        return  "/" + minioConfig.getBucketName() + "/" + objectName;
    }

    /**
     * 构建minIOClient对象
     * @return
     */
    @NotNull
    private MinioClient getMinioClient() {
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint("http://" + minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                        .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                        .build();
        return minioClient;
    }

}